package com.example.springbootdemo.utils;

import org.jxls.builder.xls.XlsCommentAreaBuilder;
import org.jxls.common.Context;
import org.jxls.expression.JexlExpressionEvaluator;
import org.jxls.transform.Transformer;
import org.jxls.transform.poi.PoiTransformer;
import org.jxls.util.JxlsHelper;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

/**
 * @Description: Excel导出工具类
 * @Author: Anonymous
 * @Time: 2019-11-04 19:35
 */
public class JxlsUtils {
    static {
        XlsCommentAreaBuilder.addCommandMapping("merge", MergeCommand.class);
    }

    public static void exportExcel(InputStream is, OutputStream os, Map<String, Object> model) throws IOException {
        Context context = PoiTransformer.createInitialContext();
        if (model != null) {
            for (Map.Entry<String, Object> entry : model.entrySet()) {
                context.putVar(entry.getKey(), entry.getValue());
            }
        }
        JxlsHelper jxlsHelper = JxlsHelper.getInstance();
        Transformer transformer = jxlsHelper.createTransformer(is, os);
        //获得配置
        JexlExpressionEvaluator evaluator = (JexlExpressionEvaluator) transformer.getTransformationConfig().getExpressionEvaluator();
        evaluator.getJexlEngine().setSilent(true);
        Map<String, Object> funcs = new HashMap<String, Object>();
        funcs.put("jx", new JxlsUtils());
        evaluator.getJexlEngine().setFunctions(funcs);
        jxlsHelper.setUseFastFormulaProcessor(false).processTemplate(context, transformer);
    }

    /**
     * 根据File类型导出
     *
     * @param templateFile
     * @param exportFile
     * @param model
     * @throws Exception
     */
    public static void exportByFile(File templateFile, File exportFile, Map<String, Object> model) throws Exception {
        if (templateFile.exists()) {
            exportExcel(new FileInputStream(templateFile), new FileOutputStream(exportFile), model);
        } else {
            throw new Exception("Excel模板未找到。");
        }

    }

    /**
     * 根据File路径导出
     *
     * @param templatePath
     * @param exportPath
     * @param model
     * @throws Exception
     */
    public static void exportByPath(String templatePath, String exportPath, Map<String, Object> model) throws Exception {
        OutputStream os = new FileOutputStream(exportPath);
        File template = new File(templatePath);
        if (template.exists()) {
            exportExcel(new FileInputStream(template), os, model);
            os.close();
        } else {
            throw new Exception("Excel模板未找到。");
        }
    }

    /**
     * 下载excel文件
     *
     * @param excelPath excel文件路径
     * @param excelName excel文件名
     * @param response
     */
    public static void downloadExcel(String excelPath, String excelName, HttpServletResponse response) {
        try (InputStream fis = new BufferedInputStream(new FileInputStream(excelPath))) {
            byte[] buffer;
            buffer = new byte[fis.available()];
            fis.read(buffer);
            response.reset();
            OutputStream os = new BufferedOutputStream(response.getOutputStream());
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(excelName, "UTF-8"));
            response.setContentType("application/vnd.ms-excel;charset=utf-8");// 定义输出类型
            os.write(buffer);
            os.flush();
            os.close();
        } catch (Exception e) {
            LogUtil.info("文件下载失败" + e);
        } finally {
            try {
                File file = new File(excelPath);
                file.delete();
            } catch (Exception e) {
                LogUtil.info("文件删除失败" + e);
            }
        }
    }

    public static String symbol(boolean b) {
        if (b)
            return "■";
        else
            return "□";
    }

}
